package com.linzm.leetcode.mid.tree.层次遍历;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author zimingl
 * @Date 2023/2/20 23:41
 * @Description: 给定一个 N 叉树，返回其节点值的层序遍历。（即从左到右，逐层遍历）。
 * 树的序列化输入是用层序遍历，每组子节点都由 null 值分隔（参见示例）。
 */
public class LevelOrder429 {
    public static void main(String[] args) {

    }

    class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    private List<List<Integer>> levelOrder2(Node root) {
        if (root == null) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        Deque<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int len = queue.size();
            while (len > 0) {
                root = queue.poll();
                list.add(root.val);
                for (Node node : root.children) {
                    queue.add(node);
                }
                len--;
            }
            res.add(list);
        }
        return res;
    }

    private List<List<Integer>> levelOrder3(Node root) {
        if (root == null) return new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        dfs(root, res, 0);
        return res;
    }

    private void dfs(Node treeNode, List<List<Integer>> res, int depth) {
        if (treeNode == null) return;
        depth++;
        if (depth > res.size()) {
            List<Integer> list = new ArrayList<>();
            res.add(list);
        }
        res.get(depth - 1).add(treeNode.val);
        for (Node node : treeNode.children) {
            dfs(node, res, depth);
        }
    }
}
